package com.tuling.mall.user.controller;

import com.tuling.mall.common.R;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
@RequestMapping("/user")
@RestController
public class OkHttpClientController {

    @RequestMapping("/findOrder/{userId}")
    public R findOrder(@PathVariable("userId") String userId) throws IOException {

        String url = "http://localhost:8010/order/findOrderByUserId/" + userId;

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                //连接超时 设置
                .connectTimeout(30, TimeUnit.SECONDS)
                //读取超时
                .readTimeout(30, TimeUnit.SECONDS)
                //写超时
                .writeTimeout(30, TimeUnit.SECONDS).build();
        Request request = new Request.Builder().url(url)//如果需要 可以在url上拼接参数
                .get()//默认为GET请求，可以不写
                //.headers() 设置头文件
                .build();
        // Call call = okHttpClient.newCall(request);
        // Response execute = call.execute();
        // 启用请求 并且获取响应体结果 来做出处理
        Response execute = okHttpClient.newCall(request).execute();
        //获取请求
        ResponseBody responseBody = execute.body();
        //结果转换为 为json结构
        assert responseBody != null;
        String body = responseBody.string();

        System.out.println(body);

        return R.success();
    }
}
